package com.file.channelTest;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.lang.reflect.Field;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

import static com.sun.nio.file.ExtendedOpenOption.DIRECT;
import static com.sun.nio.file.ExtendedOpenOption.NOSHARE_WRITE;


public class AlignedFileReader {

    private static final int SECTOR_SIZE = 512;

    public static void main(String[] args) {
        Path path = Paths.get("D:\\test.txt");

        try {
            FileChannel rw = new RandomAccessFile("D:\\test.txt", "rw").getChannel();
            MappedByteBuffer map = rw.map(FileChannel.MapMode.READ_WRITE, 0, 14096);
            map.put(100,"sdfdsf11111111111111111111111111111111111111111111111sdfdsf11111111111111111111111111111111111111111111111sdfdsf11111111111111111111111111111111111111111111111sdfdsf11111111111111111111111111111111111111111111111sdfdsf11111111111111111111111111111111111111111111111sdfdsf11111111111111111111111111111111111111111111111sdfdsf11111111111111111111111111111111111111111111111".getBytes());
            map.force();
            map.load();

            // ... 处理 alignedBuffer 中的数据 ...

        } catch (IOException e) {
            System.err.println("IO error occurred: " + e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            System.err.println("Unexpected error: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 获取 DirectByteBuffer 的内存地址，并计算对齐偏移量
     */
    private static int getAlignmentOffset(ByteBuffer buffer) throws Exception {
        if (!buffer.isDirect()) {
            throw new IllegalArgumentException("Buffer must be a direct buffer.");
        }

        // 获取 DirectByteBuffer 的 address 字段
        Field addressField = buffer.getClass().getDeclaredField("address");
        addressField.setAccessible(true);
        long address = addressField.getLong(buffer);

        // 计算对齐偏移量
        int alignmentOffset = (int) (address % SECTOR_SIZE);
        if (alignmentOffset > 0) {
            alignmentOffset = SECTOR_SIZE - alignmentOffset;
        }

        return alignmentOffset;
    }
}
